package com.marvels.financial.loan.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dragon.app.ykd.dto.AcLoanApplyNode;
import com.dragon.app.ykd.service.ClientAppService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.dragon.app.ykd.constant.ApplyNode;
import com.dragon.app.ykd.service.AcLoanApplyNodeService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.marvels.approve.loan.dao.IMcamLoanApplyInfoDao;
import com.marvels.common.constants.FundSource;
import com.marvels.common.constants.LoanStateConstant;
import com.marvels.common.constants.PageConstant;
import com.marvels.common.constants.RedisKeyConstant;
import com.marvels.common.dto.MarvelsResultDTO;
import com.marvels.common.dto.SynLoanStatus2ApplyDTO;
import com.marvels.common.dto.UserDTO;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.exception.MarvelsErrorCode;
import com.marvels.common.utils.CacheUtils;
import com.marvels.common.utils.DateUtils;
import com.marvels.common.utils.GenerateReqNoUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.financial.funds.dao.IFundDao;
import com.marvels.financial.funds.dto.FundDTO;
import com.marvels.financial.loan.api.FinancialILoanAfterInfoApi;
import com.marvels.financial.consum.FinancialConsumerApproveApi;
import com.marvels.financial.consum.FinancialConsumerLoanApplyApi;
import com.marvels.financial.loan.dao.McfeLendingProcessLogDao;
import com.marvels.financial.loan.dao.McfeLendingProcessDao;
import com.marvels.financial.loan.dto.FeeRateDTO;
import com.marvels.financial.loan.dto.LoanAfterInfoDTO;
import com.marvels.financial.loan.dto.LoanAuditConditionDto;
import com.marvels.financial.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.financial.loan.dto.McfeFundLimitDto;
import com.marvels.financial.loan.dto.McfeLendingProcess;
import com.marvels.financial.loan.dto.McfeLendingProcessLog;
import com.marvels.financial.loan.service.ILoanApplyMqProduct;
import com.marvels.financial.loan.service.LoanAuditApi;
import com.marvels.loanapply.dao.AcLoanApplyInfoDao;
import com.marvels.loanapply.dto.AcLoanApplyInfoDTO;


@Service
public class LoanAuditImpl implements LoanAuditApi {

	@Autowired
	private McfeLendingProcessDao mcfeLendingProcessMapper;

	@Autowired
	private FinancialConsumerApproveApi financialConsumerApproveApi;

	@Autowired
	private McfeLendingProcessLogDao mcfeLendingProcessLogMapper;

	@Autowired
	private FinancialILoanAfterInfoApi loanAfterInfoApi;

	@Autowired
	private IFundDao fundDao;

	@Autowired
	private FinancialILoanAfterInfoApi financialILoanAfterInfoApi;

	@Autowired
	private FinancialConsumerLoanApplyApi consumerLoanApplyApi;

	@Autowired
	private McfeLendingProcessDao mcfeLendingProcessDao;

	@Autowired
	private ILoanApplyMqProduct iLoanApplyMqProduct;

	@Autowired
	private IMcamLoanApplyInfoDao iMcamLoanApplyInfoDao;
	@Autowired
	private AcLoanApplyInfoDao acLoanApplyInfoDao;

	@Autowired
	private AcLoanApplyNodeService acLoanApplyNodeService;
	@Autowired
	private ClientAppService clientAppService;

	@Override
	public MarvelsResultDTO applyingList(LoanAuditConditionDto loanAuditConditionDto) throws MarvelsBusinessException{
		int pageSize=Integer.parseInt(loanAuditConditionDto.getPageSize());
		int pageNum=Integer.parseInt(loanAuditConditionDto.getPageNum());
		if ( pageSize< 1) {
			pageSize=PageConstant.PAGESIZE;
		}
		if (pageNum< 1) {
			pageNum=PageConstant.CURRPAGE;
		}
		PageHelper.startPage(pageNum,pageSize);
		loanAuditConditionDto.setLendProcessStatus("F0");//申请中
		Page<McfeLendingProcess> dataList = mcfeLendingProcessMapper.selectLendProcessList(loanAuditConditionDto);
		Map<String, Object> map = new HashMap<String, Object>();
		BigDecimal loanAmountTotal=new BigDecimal("0.00");//当前页贷款总金额
		BigDecimal aviAmountTotal=new BigDecimal("0.00");//当前页到手总金额
		BigDecimal consultingeeFTotal=new BigDecimal("0.00");//咨询费总金额
		if(dataList!=null && dataList.size()>0){
			for(McfeLendingProcess mcfeLendingProcess:dataList){
				loanAmountTotal=loanAmountTotal.add(mcfeLendingProcess.getPrincipalAmtAct());
				aviAmountTotal=aviAmountTotal.add(mcfeLendingProcess.getAviAmount());
				consultingeeFTotal=consultingeeFTotal.add(mcfeLendingProcess.getConsultingFee());
			}
		}
		McfeLendingProcess process=new McfeLendingProcess();
		process.setAviAmount(aviAmountTotal.setScale(2, BigDecimal.ROUND_HALF_UP));
		process.setPrincipalAmtAct(loanAmountTotal.setScale(2, BigDecimal.ROUND_HALF_UP));
		process.setConsultingFee(consultingeeFTotal.setScale(2, BigDecimal.ROUND_HALF_UP));
		process.setSelection("当前页合计");
		List<McfeLendingProcess> statisticsList=new ArrayList<McfeLendingProcess>();
		statisticsList.add(process);
		map.put("statisticsList",statisticsList);
		map.put("applyingList", dataList);
		map.put("total",dataList==null?0:dataList.getTotal());
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(),
				map);
	}

	/**
	 * 申请审核
	 */
	@Transactional(rollbackFor=Exception.class)
	public MarvelsResultDTO executeApplyAudist(LoanAuditConditionDto loanAuditConditionDto) throws MarvelsBusinessException{
		String loands = loanAuditConditionDto.getLoanIds();
		if (StringUtils.isEmpty(loands)) {
			return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), "请至少选择一项进行操作", null);
		}
		if ("1".equals(loanAuditConditionDto.getOperationStatus())) {// 审核通过
			return auditSuccessDeal(loands,loanAuditConditionDto.getLendType());
		}else if ("2".equals(loanAuditConditionDto.getOperationStatus())) {// 审核拒绝
			return auditRefuseDeal(loands);
		} else if ("3".equals(loanAuditConditionDto.getOperationStatus())) {// 审核取消
			return cancleLoanDeal(loands);
		} else if ("4".equals(loanAuditConditionDto.getOperationStatus())) {// 手动代付
			return handPayDeal(loands);
		} else {
			return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), "审核状态异常", null);
		}
	}



	@Override
	public HSSFWorkbook downLoadXsl(LoanAuditConditionDto loanAuditConditionDto) throws MarvelsBusinessException{
		List<McfeLendingProcess> list = new ArrayList<McfeLendingProcess>();
		loanAuditConditionDto.setLendProcessStatus("F0");//申请中
		if ("1".equals(loanAuditConditionDto.getExportOperation())) {// 下载当前页
			PageHelper.startPage(Integer.parseInt(loanAuditConditionDto.getPageNum()), Integer.parseInt(loanAuditConditionDto.getPageSize()));
			list = mcfeLendingProcessMapper.selectLendProcessList(loanAuditConditionDto);
			return getExcelCurrent(list);
		} else if ("2".equals(loanAuditConditionDto.getExportOperation())) {// 下载所有数据
			list = mcfeLendingProcessMapper.selectLendProcessList(loanAuditConditionDto);
			return getExcelTotal(list);
		}
		return null;
	}


	/**
	 * 审核通过处理
	 * @param loands
	 * @return
	 */
	public  MarvelsResultDTO auditSuccessDeal(String loands,String lendType) throws MarvelsBusinessException{
		if (StringUtils.isEmpty(loands)) {
			throw new MarvelsBusinessException("进件单号不能为空");
		}
		UserDTO user = null;
		try {
			CacheUtils.getCacheUser();
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().info(">>>>>>获取用户token为空");
		}
		List<String> loanList = Arrays.asList(loands.substring(0, loands.length()).split(","));
		for (String loanId : loanList) {
			// 加锁 避免重复插入数据
			String key = RedisKeyConstant.LOAN_AUDIT_HAND_PAY + loanId;
			boolean isNotLock = false;
			try {
				isNotLock = CacheUtils.isNotLock(key, loanId);
				if (isNotLock) {
					// 先将这个key设置过期时间
					CacheUtils.setExpire(key, 60);
					McfeLendingProcess mcfeLendingProcess = mcfeLendingProcessMapper.selectByloanIdAndStatus(loanId,
							"F0");
					if(mcfeLendingProcess==null){
						MarvelsLogUtil.getInstance().info(">>>>>>>>>loanId:"+loanId+",不在待审核状态");
						continue;
					}
					// 先判断限额
					boolean isExceed = judgeLoanLimit(mcfeLendingProcess.getAviAmount(),
							mcfeLendingProcess.getFundSource() + "");
					if (isExceed) {// 超出限额
						throw new MarvelsBusinessException("资金源超出限额");
					}
					mcfeLendingProcess = new McfeLendingProcess();
					mcfeLendingProcess.setStatus("F7");
					mcfeLendingProcess.setUpdatedBy(user==null?"system":user.getUserName());
					mcfeLendingProcess.setOriginalStatus("F0");
					mcfeLendingProcess.setLoanId(loanId);
					mcfeLendingProcess.setLendType(lendType);//放款类型
					mcfeLendingProcess.setPassTime(new Date());
					int countInsert = mcfeLendingProcessMapper.updateAuditResult(mcfeLendingProcess);
					if (countInsert < 1) {
						throw new MarvelsBusinessException("审核失败");
					}
					if (!auditCommonDeal(loanId, "F7", "F0", "审核通过", user)) {
						return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), "审核失败", null);
					}
				}
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error(">>>>>loanId:" + loanId + ",放款审核异常:", e);
				throw new MarvelsBusinessException(e.getMessage());
			} finally {
				if (!CacheUtils.isNotLock(key, loanId)) {// 如果是锁住的将所释放
					CacheUtils.del(key);
				}
			}

		}
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), "审核成功", null);
	}




	/**
	 * 审核拒绝处理
	 * @param loands
	 * @return
	 */
	public MarvelsResultDTO auditRefuseDeal(String loands) throws MarvelsBusinessException{
		List<String> loanList = Arrays.asList(loands.substring(0, loands.length()).split(","));
		MarvelsLogUtil.getInstance().info(loands.toString());
		UserDTO user = CacheUtils.getCacheUser();
		for (String loanId : loanList) {
			// 加锁 避免重复插入数据
			String key = RedisKeyConstant.LOAN_AUDIT_REFUSE + loanId;
			boolean isNotLock = false;
			try {
				isNotLock = CacheUtils.isNotLock(key, loanId);
				if (isNotLock) {
					// 先将这个key设置过期时间
					CacheUtils.setExpire(key, 60);
					McfeLendingProcess mcfeLendingProcess = mcfeLendingProcessMapper.selectByloanIdAndStatus(loanId,
							"F0");
					if(mcfeLendingProcess==null){
						MarvelsLogUtil.getInstance().info(">>>>>>>>>loanId:"+loanId+",不在待审核状态");
						continue;
					}
					// 修改放款申请表状态
					mcfeLendingProcess = new McfeLendingProcess();
					mcfeLendingProcess.setStatus("F1");
					mcfeLendingProcess.setUpdatedBy(user.getUserName());
					mcfeLendingProcess.setOriginalStatus("F0");
					mcfeLendingProcess.setLoanId(loanId);
					mcfeLendingProcess.setPassTime(new Date());
					int countInsert = mcfeLendingProcessMapper.updateAuditResult(mcfeLendingProcess);
					if (countInsert < 1) {
						throw new MarvelsBusinessException(">>>>>loanId:" + loanId + "审核拒绝处理持久化放款申请表失败");
					}
					if (!auditCommonDeal(loanId, "F1", "F0", "审核拒绝", user)) {
						return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), "审核失败", null);
					}
					// 修改进件表状态
//					McamLoanApplyInfoDTO mcamLoanApplyInfoDTO = new McamLoanApplyInfoDTO();
//					mcamLoanApplyInfoDTO.setLoanId(loanId);
//					mcamLoanApplyInfoDTO.setStatus("FR0");
//					mcamLoanApplyInfoDTO.setOriginalState("F03");
//					mcamLoanApplyInfoDTO.setUpdatedBy(user.getUserName());
//					int count = financialConsumerApproveApi.modifyLoanApplyInfo(mcamLoanApplyInfoDTO);
//					if (count < 1) {
//						throw new MarvelsBusinessException(">>>>>loanId:" + loanId + "审核拒绝处理失败");
//					}
					//更新ac_trace状态为审核拒绝处理
					SynLoanStatus2ApplyDTO synLoanStatus2ApplyDTO=new SynLoanStatus2ApplyDTO();
					synLoanStatus2ApplyDTO.setLoanId(loanId);
					synLoanStatus2ApplyDTO.setOriginalState(LoanStateConstant.F03);
					synLoanStatus2ApplyDTO.setStatus(LoanStateConstant.FR0);
					iLoanApplyMqProduct.synLoanStatus2Apply(synLoanStatus2ApplyDTO);
					AcLoanApplyNode acLoanApplyNode = new AcLoanApplyNode();
					acLoanApplyNode.setLoanId(loanId);
					acLoanApplyNode.setNodeCode(ApplyNode.LOAN_REfUSE.getCode());
					acLoanApplyNode.setNodeMsg(ApplyNode.LOAN_REfUSE.getMsg());
					clientAppService.addLoanApplyNode(acLoanApplyNode);


				}
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error(">>>>>loanId:" + loanId + ",审核拒绝处理异常:", e);
				throw new MarvelsBusinessException(e.getMessage());
			} finally {
				if (!CacheUtils.isNotLock(key, loanId)) {// 如果是锁住的将所释放
					CacheUtils.del(key);
				}
			}
		}
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), "审核拒绝处理成功", null);
	}




	/**
	 * 取消放款处理
	 * @param loands
	 * @return
	 */
	public MarvelsResultDTO cancleLoanDeal(String loands) throws MarvelsBusinessException{
		List<String> loanList = Arrays.asList(loands.substring(0, loands.length()).split(","));
		UserDTO user = CacheUtils.getCacheUser();
		for (String loanId : loanList) {
			// 加锁 避免重复插入数据
			String key = RedisKeyConstant.LOAN_AUDIT_CANCLE + loanId;
			boolean isNotLock = false;
			try {
				isNotLock = CacheUtils.isNotLock(key, loanId);
				if (isNotLock) {
					// 先将这个key设置过期时间
					CacheUtils.setExpire(key, 60);
					// 修改放款申请表状态
					McfeLendingProcess mcfeLendingProcess = new McfeLendingProcess();
					mcfeLendingProcess.setStatus("F6");
					mcfeLendingProcess.setUpdatedBy(user.getUserName());
					mcfeLendingProcess.setOriginalStatus("F0");
					mcfeLendingProcess.setLoanId(loanId);
					mcfeLendingProcess.setPassTime(new Date());
					int countInsert = mcfeLendingProcessMapper.updateAuditResult(mcfeLendingProcess);
					if (countInsert < 1) {
						throw new MarvelsBusinessException(">>>>>loanId:" + loanId + "审核拒绝处理持久化放款申请表失败");
					}
					if (!auditCommonDeal(loanId, "F6", "F0", "取消放款", user)) {
						throw new MarvelsBusinessException(">>>>>loanId:" + loanId + "取消放款处理失败");
					}

					// 修改进件表状态
//					McamLoanApplyInfoDTO mcamLoanApplyInfoDTO = new McamLoanApplyInfoDTO();
//					mcamLoanApplyInfoDTO.setLoanId(loanId);
//					mcamLoanApplyInfoDTO.setStatus("F81");
//					mcamLoanApplyInfoDTO.setOriginalState("F03");
//					mcamLoanApplyInfoDTO.setUpdatedBy(user.getUserName());
//					int count = financialConsumerApproveApi.modifyLoanApplyInfo(mcamLoanApplyInfoDTO);
//					if (count < 1) {
//						throw new MarvelsBusinessException(">>>>>loanId:" + loanId + "取消放款处理失败");
//					}
					//更新ac_trace状态为取消放款
					SynLoanStatus2ApplyDTO synLoanStatus2ApplyDTO=new SynLoanStatus2ApplyDTO();
					synLoanStatus2ApplyDTO.setLoanId(loanId);
					synLoanStatus2ApplyDTO.setOriginalState(LoanStateConstant.F03);
					synLoanStatus2ApplyDTO.setStatus(LoanStateConstant.F81);
					iLoanApplyMqProduct.synLoanStatus2Apply(synLoanStatus2ApplyDTO);
					AcLoanApplyNode acLoanApplyNode = new AcLoanApplyNode();
					acLoanApplyNode.setLoanId(loanId);
					acLoanApplyNode.setNodeCode(ApplyNode.LOAN_CANCEL.getCode());
					acLoanApplyNode.setNodeMsg(ApplyNode.LOAN_CANCEL.getMsg());
					clientAppService.addLoanApplyNode(acLoanApplyNode);
				}
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error(">>>>>loanId:" + loanId + ",取消放款处理异常:", e);
				throw new MarvelsBusinessException(e.getMessage());
			} finally {
				if (!CacheUtils.isNotLock(key, loanId)) {// 如果是锁住的将所释放
					CacheUtils.del(key);
				}
			}
		}
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), "取消放款处理成功", null);
	}



	/**
	 * 手动代付处理
	 * @param loands
	 * @return
	 */
	public MarvelsResultDTO handPayDeal(String loands) throws MarvelsBusinessException{
		List<String> loanList = Arrays.asList(loands.substring(0, loands.length()).split(","));
		for (String loanId : loanList) {
			// 加锁 避免重复插入数据
			String key =RedisKeyConstant.LOAN_AUDIT_HAND_PAY + loanId;
			boolean isNotLock = false;
			try {
				isNotLock = CacheUtils.isNotLock(key, loanId);
				if (isNotLock) {
					// 先将这个key设置过期时间
					CacheUtils.setExpire(key, 60);
					McfeLendingProcess mcfeLendingProcess = mcfeLendingProcessMapper.selectByloanIdAndStatus(loanId,
							"F0");
					if(mcfeLendingProcess==null){
						MarvelsLogUtil.getInstance().info(">>>>>>>>>loanId:"+loanId+",不在待审核状态");
						continue;
					}
					// 查询进件表信息
					McamLoanApplyInfoDTO applyInfoDTO = new McamLoanApplyInfoDTO();
					applyInfoDTO.setLoanId(loanId);
					McamLoanApplyInfoDTO infoDTO = financialConsumerApproveApi.selectLoanApplyInfo(applyInfoDTO);
					// 不需要修改进件表状态(直接生成还款计划生成还款计划修改) 调用生成还款计划
					try {
						LoanAfterInfoDTO LoanAfterInfoDTO = new LoanAfterInfoDTO();
						LoanAfterInfoDTO.setLoanId(loanId);
						LoanAfterInfoDTO.setProductCode(infoDTO.getProductCode());
						LoanAfterInfoDTO.setFundSource(infoDTO.getFundCode());
						LoanAfterInfoDTO.setTenor(infoDTO.getApplyTerms());
						LoanAfterInfoDTO.setDate(new Date());
						LoanAfterInfoDTO.setAmount(infoDTO.getPrincipalAmtAct());
						LoanAfterInfoDTO.setFundName(infoDTO.getFundName());//资金源名称
						LoanAfterInfoDTO.setProductName(infoDTO.getProductName());//产品小类名称
						LoanAfterInfoDTO.setCustCardNo(infoDTO.getCustCardNo());//客户身份证号
						LoanAfterInfoDTO.setCustName(infoDTO.getCustName());//客户名称
						LoanAfterInfoDTO.setChannelCode(infoDTO.getChannel());//渠道code
						LoanAfterInfoDTO.setChannelName(infoDTO.getChannelName());//渠道名称
						LoanAfterInfoDTO.setProductType(infoDTO.getProductType());//产品大类code
						LoanAfterInfoDTO.setProductTypeName(infoDTO.getProductTypeName());//产品大类名称
						LoanAfterInfoDTO.setMobile(infoDTO.getMobileNo());//客户电话
						LoanAfterInfoDTO.setPaymentBankBranch(infoDTO.getPaymentBankBranch());//还款账户分行联行号
						LoanAfterInfoDTO.setPaymentBankHead(infoDTO.getPaymentBankHead());//还款账户总行联行号
						LoanAfterInfoDTO.setPaymentAcctNo(infoDTO.getPaymentAcctNo());//还款账户卡号
						LoanAfterInfoDTO.setPaymentBankName(infoDTO.getPaymentBankName());//还款账户开户行名称
						LoanAfterInfoDTO.setPaymentAcctName(infoDTO.getPaymentAcctName());//还款账户名称
						LoanAfterInfoDTO.setPatternType(infoDTO.getPatternCode());
						loanAfterInfoApi.loanApplySuccess(LoanAfterInfoDTO);
					} catch (Exception e) {
						MarvelsLogUtil.getInstance().error(">>>>>>>>>>loanId:" + "loanId" + "手动代付处理生成还款计划异常:", e);
						return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), "生成还款计划异常", null);
					}
					UserDTO user = CacheUtils.getCacheUser();
					// 修改放款申请表状态
					mcfeLendingProcess = new McfeLendingProcess();
					mcfeLendingProcess.setStatus("F4");
					mcfeLendingProcess.setUpdatedBy(user.getUserName());
					mcfeLendingProcess.setOriginalStatus("F0");
					mcfeLendingProcess.setLoanId(loanId);
					mcfeLendingProcess.setPassTime(new Date());
					//手动放款
					mcfeLendingProcess.setLendType("2");
					try {
						String reloanFlag =  consumerLoanApplyApi.synchroMoneyHandOutTime(loanId);
						mcfeLendingProcess.setReloanFlag(reloanFlag);
					} catch (Exception e) {
						MarvelsLogUtil.getInstance().error(">>>>>>>>>>loanId:" + loanId + "同步到进件表的放款时间失败:", e);
					}
					int countInsert = mcfeLendingProcessMapper.updateAuditResult(mcfeLendingProcess);
					if (countInsert < 1) {
						throw new MarvelsBusinessException(">>>>>loanId:" + loanId + "手动代付处理持久化放款申请表失败");
					}
					if (!auditCommonDeal(loanId, "F2", "F0", "手动放款", user)) {
						throw new MarvelsBusinessException(">>>>>loanId:" + loanId + "手动代付处理失败");
					}

					// 流程新流程节点（贷款确认）
					acLoanApplyNodeService.insertSelective(loanId, ApplyNode.LOAN_REPAYMENT);
				}
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error(">>>>>loanId:" + loanId + ",手动代付处理异常:", e);
				throw new MarvelsBusinessException("手动代付处理异常");
			} finally {
				if (!CacheUtils.isNotLock(key, loanId)) {// 如果是锁住的将所释放
					CacheUtils.del(key);
				}
			}
		}
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), "手动代付处理成功", null);
	}


	/**
	 * 审核通用方法
	 * @param loanId
	 * @param status 处理结果状态
	 * @param user
	 * @param processPhase 流程阶段
	 * @return
	 */
	public boolean auditCommonDeal(String loanId,String status,String originalStatus,String processPhase,UserDTO user){
		String userName="";
		if(user!=null){
			userName=user.getUserName();
		}else{
			userName="system";
		}
		//修改放款申请日志结束时间
		McfeLendingProcessLog mcfeLendingProcessLog=new McfeLendingProcessLog();
		mcfeLendingProcessLog.setUpdatedBy(userName);
		mcfeLendingProcessLog.setLoanId(loanId);
		mcfeLendingProcessLog.setOriginalStatus(originalStatus);
		int countUpdateLog=mcfeLendingProcessLogMapper.updateLendingProcessLog(mcfeLendingProcessLog);
		if(countUpdateLog<1){
			return false;
		}
		//记录新的放款处理日志
		mcfeLendingProcessLog.setStatus(status);
		mcfeLendingProcessLog.setCreatedBy(userName);
		mcfeLendingProcessLog.setHandlerUser(userName);
		mcfeLendingProcessLog.setLoanId(loanId);
		mcfeLendingProcessLog.setCreatedDate(new Date());
		mcfeLendingProcessLog.setUpdatedDate(new Date());
		mcfeLendingProcessLog.setStartTime(new Date());
		mcfeLendingProcessLog.setProcessPhase(processPhase);
		int countInsertCount=mcfeLendingProcessLogMapper.insertSelective(mcfeLendingProcessLog);
		if(countInsertCount<1){
			return false;
		}
		return true;
	}



	/**
	 * 下载所有数据的excel
	 * @param list
	 * @return
	 * @throws MarvelsBusinessException
	 */
	public HSSFWorkbook getExcelTotal(List<McfeLendingProcess> list) throws MarvelsBusinessException{
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("放款审核数据一览表");
		HSSFRow row = sheet.createRow((int) 0);
		sheet.setDefaultColumnWidth(10);
		// 创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		// 居中格式、加粗
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		org.apache.poi.hssf.usermodel.HSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 11);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style.setBorderBottom((short) 1);// 下边框
		style.setBorderLeft((short) 1);// 左边框
		style.setBorderRight((short) 1);// 右边框
		style.setBorderTop((short) 1);// 上边框
		style.setLocked(true);
		style.setFont(font);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("姓名");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("身份证号");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("银行卡号");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("开户行");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("产品");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("合同金额");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("到手金额");
		cell.setCellStyle(style);
		cell = row.createCell(7);
		cell.setCellValue("咨询费");
		cell.setCellStyle(style);
		cell = row.createCell(8);
		cell.setCellValue("期限");
		cell.setCellStyle(style);
		cell = row.createCell(9);
		cell.setCellValue("申请时间");
		cell.setCellStyle(style);
		cell = row.createCell(10);
		cell.setCellValue("申请人");
		cell.setCellStyle(style);
		cell = row.createCell(11);
		cell.setCellValue("资金方");
		cell.setCellStyle(style);
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				row = sheet.createRow((int) i + 1);
				// 创建单元格，并设置值
				row.createCell(0).setCellValue(list.get(i).getCustName());
				row.createCell(1).setCellValue(list.get(i).getCustCardNo());
				row.createCell(2).setCellValue(list.get(i).getReceiveAcctNo());
				row.createCell(3).setCellValue(list.get(i).getReceiveBankName());
				row.createCell(4).setCellValue(list.get(i).getProductName());
				row.createCell(5).setCellValue(list.get(i).getPrincipalAmtAct() + "");
				row.createCell(6).setCellValue(list.get(i).getAviAmount() + "");
				row.createCell(7).setCellValue(list.get(i).getConsultingFee() + "");
				row.createCell(8).setCellValue(list.get(i).getTerms() + "");
				row.createCell(9).setCellValue(DateUtils.getDateStr(list.get(i).getCreatedDate(), "yyyy-mm-dd"));
				row.createCell(10).setCellValue(list.get(i).getCreatedBy());
				row.createCell(11).setCellValue(list.get(i).getFundName());
			}
		}
		return wb;
	}




	/**
	 * 下载当前数据的excel
	 * @param list
	 * @return
	 * @throws MarvelsBusinessException
	 */
	public HSSFWorkbook getExcelCurrent(List<McfeLendingProcess> list) throws MarvelsBusinessException{
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("放款审核数据一览表");
		HSSFRow row = sheet.createRow((int) 0);
		sheet.setDefaultColumnWidth(10);
		// 创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		// 居中格式、加粗
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		org.apache.poi.hssf.usermodel.HSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 11);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style.setBorderBottom((short) 1);// 下边框
		style.setBorderLeft((short) 1);// 左边框
		style.setBorderRight((short) 1);// 右边框
		style.setBorderTop((short) 1);// 上边框
		style.setLocked(true);
		style.setFont(font);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("姓名");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("身份证号");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("银行卡号");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("开户行");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("产品");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("合同金额");
		cell.setCellStyle(style);
		cell = row.createCell(7);
		cell.setCellValue("到手金额");
		cell.setCellStyle(style);
		cell = row.createCell(8);
		cell.setCellValue("咨询费");
		cell.setCellStyle(style);
		cell = row.createCell(9);
		cell.setCellValue("期限");
		cell.setCellStyle(style);
		cell = row.createCell(10);
		cell.setCellValue("申请时间");
		cell.setCellStyle(style);
		cell = row.createCell(11);
		cell.setCellValue("申请人");
		cell.setCellStyle(style);
		cell = row.createCell(12);
		cell.setCellValue("资金方");
		cell.setCellStyle(style);
		BigDecimal loanAmountTotal=new BigDecimal("0.00");//当前页贷款总金额
		BigDecimal aviAmountTotal=new BigDecimal("0.00");//当前页到手总金额
		BigDecimal consultingeeFTotal=new BigDecimal("0.00");//咨询费总金额
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				row = sheet.createRow((int) i + 1);
				// 创建单元格，并设置值
				row.createCell(0).setCellValue("");
				row.createCell(1).setCellValue(list.get(i).getCustName());
				row.createCell(2).setCellValue(list.get(i).getCustCardNo());
				row.createCell(3).setCellValue(list.get(i).getReceiveAcctNo());
				row.createCell(4).setCellValue(list.get(i).getReceiveBankName());
				row.createCell(5).setCellValue(list.get(i).getProductName());
				row.createCell(6).setCellValue(list.get(i).getPrincipalAmtAct() + "");
				row.createCell(7).setCellValue(list.get(i).getAviAmount() + "");
				row.createCell(8).setCellValue(list.get(i).getConsultingFee() + "");
				row.createCell(9).setCellValue(list.get(i).getTerms() + "");
				row.createCell(10).setCellValue(DateUtils.getDateStr(list.get(i).getCreatedDate(), "yyyy-mm-dd"));
				row.createCell(11).setCellValue(list.get(i).getCreatedBy());
				row.createCell(12).setCellValue(list.get(i).getFundName());
				loanAmountTotal=loanAmountTotal.add(list.get(i).getPrincipalAmtAct());
				aviAmountTotal=aviAmountTotal.add(list.get(i).getAviAmount());
				consultingeeFTotal=consultingeeFTotal.add(list.get(i).getConsultingFee());
			}
		}
		row = sheet.createRow(list.size() + 1);
		row.createCell(0).setCellValue("当前页合计");
		row.createCell(6).setCellValue(loanAmountTotal+"");
		row.createCell(7).setCellValue(aviAmountTotal+"");
		row.createCell(8).setCellValue(consultingeeFTotal+"");
		return wb;
	}



	/**
	 * 判断限额
	 * @param loanAmount  放款金额
	 * @param fundCode	资金源code
	 * @return
	 * @throws MarvelsBusinessException
	 */
	@Override
	public boolean judgeLoanLimit(BigDecimal loanAmount,String fundCode) throws MarvelsBusinessException{

		//统计当天放款金额(包含代付成功, 支付中  ,处理中 ,放款成功)
		BigDecimal totalTotalAmount=mcfeLendingProcessMapper.selectTodayAmount(fundCode);

		BigDecimal dayLimit=new BigDecimal("0.0");
		//查询资金源日限额
		FundDTO fundDTO=new FundDTO();
		fundDTO.setFundCode(fundCode);
		List<McfeFundLimitDto> limitList = fundDao.selectLimitByFundCode(fundDTO);
		if(null!=limitList && limitList.size()>0){
			dayLimit=limitList.get(0).getDayLimit();
		}else{//未设置则直接返回未超限制
			return false;
		}
		if(dayLimit.compareTo(totalTotalAmount)<1){
			return true;
		}
		return false;
	}

	@Override
	public void loanAmountAdjust(LoanAuditConditionDto loanAuditConditionDto) throws MarvelsBusinessException {
		String loanId=loanAuditConditionDto.getLoanId();
		BigDecimal  loanAmountAdjust=loanAuditConditionDto.getLoanAmountAdjust();
		if(StringUtils.isEmpty(loanId)){
			throw new MarvelsBusinessException("loanId不能为空");
		}
		if(loanAmountAdjust==null){
			throw new MarvelsBusinessException("调整金额不能为空");
		}
		String key =RedisKeyConstant.LOAN_AUDIT_HAND_PAY + loanId;
		boolean isNotLock = false;
		try {
			isNotLock = CacheUtils.isNotLock(key, loanId);
			if (isNotLock) {
				// 先将这个key设置过期时间
				CacheUtils.setExpire(key, 60);
				McfeLendingProcess mcfeLendingProcess = mcfeLendingProcessMapper.selectByloanIdAndStatus(loanId,
						"F0");
				if(mcfeLendingProcess==null){
					MarvelsLogUtil.getInstance().info(">>>>>>>>>loanId:"+loanId+",不在待审核状态");
					throw new MarvelsBusinessException("进件不在待审核状态");
				}
				//更新放款申请记录
				LoanAfterInfoDTO loanAfterInfoDTO=new LoanAfterInfoDTO();
				loanAfterInfoDTO.setAmount(loanAmountAdjust);//实际借款总额
				loanAfterInfoDTO.setDate(new Date());//放款时间
				loanAfterInfoDTO.setProductCode(mcfeLendingProcess.getProductCode());//产品小类code
				loanAfterInfoDTO.setTenor(mcfeLendingProcess.getTerms());//期数
				loanAfterInfoDTO.setFundSource(String.valueOf(mcfeLendingProcess.getFundSource()));//资金源code
				loanAfterInfoDTO.setLoanId(loanId);//贷款id
				LoanAfterInfoDTO resultInfo=financialILoanAfterInfoApi.loanTrial(loanAfterInfoDTO);
				MarvelsLogUtil.getInstance().info("调整放款金额-loanTrial result ===>"+JSON.toJSONString(resultInfo));
				BigDecimal aviAmount= new BigDecimal("0.00");// 到手金额
				BigDecimal interestRate = new BigDecimal("0.00");// 利息费率
				BigDecimal consultingFeeRate = new BigDecimal("0.00");// 咨询费费率
				BigDecimal managementFeeRate = new BigDecimal("0.00");// 管理费费率
				BigDecimal penaltyFeeRate = new BigDecimal("0.00");// 违约金费率
				BigDecimal lateFeeRate = new BigDecimal("0.00");// 滞纳金费率
				BigDecimal preTerminateFeeRate = new BigDecimal("0.00");// 提前结清费费率
				BigDecimal miscFeeRate = new BigDecimal("0.00");// 杂费费率
				BigDecimal platformFeeRate = new BigDecimal("0.00");// 平台费费率
				BigDecimal fundInterestRate = new BigDecimal("0.00");// 资金源利息费率
				if(null !=resultInfo && null!=resultInfo.getFeeRateDTO()){
					FeeRateDTO feeRateDTO=resultInfo.getFeeRateDTO();
					aviAmount = resultInfo.getAviAmount();// 到手金额
					interestRate = feeRateDTO.getInterestRate();// 利息费率
					consultingFeeRate =feeRateDTO.getConsultingFeeRate();// 咨询费费率
					managementFeeRate = feeRateDTO.getManagementFeeRate();// 管理费费率
					penaltyFeeRate =feeRateDTO.getPenaltyFeeRate();// 违约金费率
					lateFeeRate = feeRateDTO.getLateFeeRate();// 滞纳金费率
					preTerminateFeeRate = feeRateDTO.getPreTerminateFeeRate();// 提前结清费费率
					miscFeeRate = feeRateDTO.getMiscFeeRate();// 杂费费率
					platformFeeRate = feeRateDTO.getPlatformFeeRate();// 平台费费率
					fundInterestRate = feeRateDTO.getFundInterestRate();// 资金源利息费率
				}
				BigDecimal consultingFee = loanAmountAdjust.subtract(aviAmount);
				McfeLendingProcess mcfeProcess=new McfeLendingProcess();
				mcfeProcess.setPrincipalAmtAct(loanAmountAdjust);
				mcfeProcess.setAviAmount(aviAmount);
				mcfeProcess.setConsultingFee(consultingFee);
				mcfeProcess.setInterestRate(interestRate);// 利息费率
				mcfeProcess.setConsultingFeeRate(consultingFeeRate);// 咨询费费率
				mcfeProcess.setManagementFeeRate(managementFeeRate);// 管理费费率
				mcfeProcess.setPenaltyFeeRate(penaltyFeeRate);// 违约金费率
				mcfeProcess.setLateFeeRate(lateFeeRate);// 滞纳金费率
				mcfeProcess.setPreTerminateFeeRate(preTerminateFeeRate);// 提前结清费费率
				mcfeProcess.setMiscFeeRate(miscFeeRate);// 杂费费率
				mcfeProcess.setPlatformFeeRate(platformFeeRate);// 平台费费率
				mcfeProcess.setFundInterestRate(fundInterestRate);// 资金源利息费率
				mcfeProcess.setId(mcfeLendingProcess.getId());
				UserDTO user = null;
				try {
					user=CacheUtils.getCacheUser();
				} catch (Exception e) {
				}
				mcfeProcess.setUpdatedBy(user.getUserCode());
				mcfeProcess.setUpdatedDate(new Date());
				int count=mcfeLendingProcessDao.updateLoanAmountAdjust(mcfeProcess);
				if(count<1){
					throw new MarvelsBusinessException("放款金额调整失败");
				}

				//修改进件表中的实际放款金额
				com.marvels.approve.loan.dto.McamLoanApplyInfoDTO mcamLoanApplyInfoDTO=new com.marvels.approve.loan.dto.McamLoanApplyInfoDTO();
				mcamLoanApplyInfoDTO.setPrincipalAmtAct(loanAmountAdjust);
				mcamLoanApplyInfoDTO.setLoanId(loanId);
				iMcamLoanApplyInfoDao.updateByLoanId(mcamLoanApplyInfoDTO);

				//修改ac_loan表中的时间放款金额
				AcLoanApplyInfoDTO acLoanApplyInfoDTO=new AcLoanApplyInfoDTO();
				acLoanApplyInfoDTO.setLoanMoneyAct(loanAmountAdjust);//实际贷款金额
				acLoanApplyInfoDTO.setUpdateTime(new Date());
				acLoanApplyInfoDTO.setLoanId(loanId);
				acLoanApplyInfoDao.modifyAcLoanApplyInfo(acLoanApplyInfoDTO);
			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>loanId:" + loanId + ",手动代付处理异常:", e);
			throw new MarvelsBusinessException("手动代付处理异常");
		} finally {
			if (!CacheUtils.isNotLock(key, loanId)) {// 如果是锁住的将所释放
				CacheUtils.del(key);
			}
		}

	}



}
